<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    //添加评论
    public function add()
    {
        if (!user_ins()->is_logged_in())
            return ['status' => 0, 'msg' => 'no login'];

        if (!rq('content'))
            return ['status' => 0, 'msg' => 'no content'];

        if ((!rq('question_id') && !rq('answer_id')) || (rq('question_id') && rq('answer_id')))
            return ['status' => 0, 'msg' => 'require question_id or answer_id'];

        if (rq('question_id')) {
            //评论问题
            $question = question_ins()->find(rq('question_id'));
            if (!$question)
                return ['status' => 0, 'msg' => 'no question'];
            $this->question_id = rq('question_id');
        } else {
            //评论答案
            $answer = answer_ins()->find(rq('answer_id'));
            if (!$answer)
                return ['status' => 0, 'msg' => 'no answer'];
            $this->answer_id = rq('answer_id');
        }

        if (rq('reply_to')) {
            //回复评论
            $target = $this->find(rq('reply_to'));
            if (!$target)
                return ['status' => 0, 'msg' => 'comment exists'];
            if ($target->user_id == session('user_id'))
                return ['status' => 0, 'msg' => 'not reply self'];
            $this->reply_to = rq('reply_to');
        }

        $this->content = rq('content');
        $this->user_id = session('user_id');
        return $this->save() ?
            ['status' => 200, 'id' => $this->id] :
            ['status' => 0, 'msg' => 'save failed'];
    }

    //read
    public function read()
    {
        if ((!rq('question_id') && !rq('answer_id')) || (rq('question_id') && rq('answer_id')))
            return ['status' => 0, 'msg' => 'require question_id or answer_id'];

        if (rq('question_id')) {
            $field = 'question_id';
            $model = question_ins();
        } else {
            $field = 'answer_id';
            $model = answer_ins();
        }
        $data = $model->find(rq($field));
        if (!$data)
            return ['status' => 0, 'msg' => $field . 'exists'];
        $data = $this->where($field, rq($field))->get()->keyBy('id');
        return ['status' => 200, 'data' => $data];
    }

    //删除评论
    public function remove()
    {
        if (!user_ins()->is_logged_in())
            return ['status => 0', 'msg' => 'no login'];

        if (!rq('id'))
            return ['status' => 0, 'msg' => 'no id'];
        $comment = $this->find(rq('id'));
        if (!$comment)
            return ['status' => 0, 'msg' => 'no comment'];
        if ($comment->user_id != session('user_id'))
            return ['status' => 0, 'msg' => 'no auth'];

        //先删除评论下的回复
        $this->where('reply_to', rq('id'))->delete();

        return $comment->delete() ?
            ['status' => 200] :
            ['status' => 0, 'msg' => 'delete fail'];
    }
}
